<script>
	import Vue from 'vue'

	import service from '@/store/service';
	import {
		showChatNotice
	} from '@/components/notice/notice-plus-show.js';
	import api from '@/api/api';
	import __config from "@/config/env";
	import JimUtil from '@/utils/jim-util' // IM工具库
	// #ifdef APP-PLUS
	import APPUpdate from "@/public/APPUpdate/index.js"; //App版本更新
	// #endif

	export default {
		globalData: {
			username: null,
			user_id: null,
			tenant_id: null,
			access_token: null,
			expires_in: null, //过期时间：该时间为当前时间之后的时间，单位为毫秒数
			permissions: {}, //权限 Object
			bgColor: 'bg-white',
			JIM: null, //IMJMessage
			IMdata: {
				IMOpenLog: false, //im日志打印
				IMplatform: '5',
				IMoperationID: '',
				IMuserID: '',
				IMtoken: '',
				IMJSwsAddr: '', //wss连接地址
				IMloginStatus: false,
				IMconnectStatus: 0, // 服务器连接状态:0,:失败;1:成功;2:连接中
				IMmessageList: [], // 会话列表
				IMheartCheckTimer: null,
				IMcheckIMLoginOK: false,
			},
			isDev: true, // 是否是开发模式,开发模式下会记录日志等显示开发模式下的操作及显示
			showApp: false, // app是否打开状态
		},
		data() {
			return {
				refreshTime: null,
				refreshLock: false
			}
		},
		onLaunch: function() {
			service.saveLogInfo("********************** App启动 ************************")
			// 版本更新检测
			// #ifdef APP-PLUS
			APPUpdate();
			// 初始化个推
			this.initUniCid()
			// #endif
			uni.getSystemInfo({
				success: function(e) {
					// #ifndef MP
					Vue.prototype.StatusBar = e.statusBarHeight;
					if (e.platform == 'android') {
						Vue.prototype.CustomBar = e.statusBarHeight + 50;
					} else {
						Vue.prototype.CustomBar = e.statusBarHeight + 45;
					};
					// #endif

					// #ifdef MP-WEIXIN
					Vue.prototype.StatusBar = e.statusBarHeight;
					let custom = wx.getMenuButtonBoundingClientRect();
					Vue.prototype.Custom = custom;
					Vue.prototype.CustomBar = custom.bottom + custom.top - e.statusBarHeight;
					// #endif

					// #ifdef MP-ALIPAY
					Vue.prototype.StatusBar = e.statusBarHeight;
					Vue.prototype.CustomBar = e.statusBarHeight + e.titleBarHeight;
					// #endif
				}
			});
			// 判断登录
			service.saveLogInfo("-----开始登录-----")
			this.startLogin();
			service.saveLogInfo("-----结束登录-----")
		},
		onShow: function() {
			console.log('App Show')
			// 初始化OpenIM
			if (this.globalData.JIM) {
				JimUtil.showAPP()
			}
			this.globalData.showApp = true
			// #ifdef APP-PLUS
			plus.push.clear();
			// #endif
		},
		onHide: function() {
			console.log('App Hide')
			if (this.globalData.JIM) {
				JimUtil.hideAPP()
			}
			this.globalData.showApp = false
		},
		methods: {
			startLogin() {
				// 登录流程--接口调用处也会判断和验证token
				// 1.如果有值就表示登录过，启动自动登录
				// 		1.1 验证token有效期(一般为7天),如果在有效期内就直接跳转到首页
				// 		1.2 如果token过期,那么就调用刷新token的接口刷新有效期
				// 		1.3 如果refresh_token(一般为30天)也过期那么就跳转到登录页面
				// 2.如果没有登录过就直接跳转到登录页面
				const loginTokenInfo = service.getLoginAccessToken();
				if (loginTokenInfo && loginTokenInfo.access_token) {
					service.saveLogInfo("-----token登录-----")
					let curDateTime = new Date().getTime();
					if (curDateTime < loginTokenInfo.expires_in) { // 1.1
						service.saveLogInfo("-----token未过期登录-----")
						let app = getApp();
						app.globalData.access_token = loginTokenInfo.access_token;
						app.globalData.username = loginTokenInfo.username;
						app.globalData.user_id = loginTokenInfo.user_id;
						app.globalData.tenant_id = loginTokenInfo.tenant_id;
						app.globalData.expires_in = loginTokenInfo.expires_in;
						// 获取个人信息
						this.getUserInfo();
					} else { //1.2
						service.saveLogInfo("-----token已过期，刷新登录-----")
						// token过期，刷新token
						api.login.refreshToken(loginTokenInfo.refresh_token).then(response => {
							service.saveLogInfo("-----token过期已刷新成功-----")
							// 登录成功 保存登录数据、本次登录的token
							service.saveAccessToken(response);
							// 获取个人信息
							this.getUserInfo();
						}).catch(response => {
							//失败 重新登录
							this.loginFail();
						});
					}
				} else {
					// 登录
					uni.reLaunch({
						url: '/pages/login/login'
					});
				}
			},
			loginFail() {
				service.removeUser();
				uni.showToast({
					icon: 'none',
					position: 'bottom',
					title: '登录失败,请重新登录'
				});
				uni.reLaunch({
					url: '/pages/login/login'
				});
			},
			getUserInfo() {
				service.saveLogInfo("-----登录成功,获取用户信息-----")
				api.getUserInfo().then(response => {
					service.saveLogInfo("-----获取用户信息成功-----")
					// 更新用户信息
					service.saveUserInfo(response.data.sysUser);
					// 保存用户权限
					service.saveUserPermissions(response.data.permissions);

					service.saveLogInfo("-----初始化JIM-----")
					// 初始化IM
					this.initJIM()
					service.saveLogInfo("-----初始化IM完成-----")
					service.saveLogInfo("-----初始化Getui-----")
					// 初始化个推
					this.initUniCid()
					service.saveLogInfo("-----初始化Getui完成-----")
				}).catch(response => {
					//失败 重新登录
					service.saveLogInfo("-----获取用户信息失败-----" + JSON.stringify(response))
					this.loginFail();
				});
			},
			//初始化OpenIM
			initJIM() {
				let that = this
				return new Promise((resolve, reject) => {
					//获取用户信息
					let userInfo = service.getUser();
					//还不是商城用户，不登录JLIM
					if (!userInfo || !userInfo.id) {
						console.log("还不是商城用户，不登录JLIM")
						resolve("success");
						return
					}
					if (this.globalData.JIM && this.globalData.IMdata && this.globalData.IMdata.IMloginStatus &&
						this.globalData.IMdata.IMconnectStatus == 1) { //OpenIM已经初始化，直接登录
						if (this.globalData.IMdata.IMOpenLog) console.log("IM已经登录")
						JimUtil.checkLoginStatus()
						resolve("success");
						return
					} else {
						// 初始化
						JimUtil.initOpenIM().then(() => {
							resolve("success");
						}).catch(() => {
							resolve("success");
						})
					}
				});
			},
			getuiAliasBind() { // 绑定个推别名
				service.saveLogInfo("-----bindGetui-----")
				service.saveLogInfo("gettuicid:" + this.globalData.uniAppClientId)
				console.log("gettuicid:" + this.globalData.uniAppClientId)
				if (this.globalData.uniAppClientId) {
					let userInfo = service.getUser();
					//还不是商城用户，不调用接口
					if (userInfo && userInfo.id) {
						console.log("绑定用户个推别名")
						service.saveLogInfo("-----绑定用户个推别名-----")
						api.mall.getuiAliasGet(this.globalData.uniAppClientId).then(res => {
							// 返回错误码说明 https://docs.getui.com/getui/server/rest_v2/code/
							if (res.code == 20001) {
								service.saveLogInfo("getuiAliasGet:20001")
								let params = {
									"dataList": [{
										"cid": this.globalData.uniAppClientId,
										"alias": JimUtil.GetIMuserID()
									}]
								}
								api.mall.getuiAliasBind(params).then(res => {
									if (res.code == 20001) {
										console.log("cid无效或者错误或者cid不是当前应用的")
										service.saveLogInfo("-----cid无效或者错误或者cid不是当前应用的-----")
									}
									service.saveLogInfo("-----getuiAliasBind-----" + res.code)
									console.log("getuiAliasBind:" + res.code)
								})
							} else {
								// 别名与cid不一致时进行绑定操作
								if (res.data.alias != JimUtil.GetIMuserID()) {
									let params = {
										"dataList": [{
											"cid": this.globalData.uniAppClientId,
											"alias": JimUtil.GetIMuserID()
										}]
									}
									api.mall.getuiAliasBind(params).then(res => {
										if (res.code == 20001) {
											console.log("cid无效或者错误或者cid不是当前应用的")
											service.saveLogInfo("-----cid无效或者错误或者cid不是当前应用的-----")
										}
										service.saveLogInfo("-----getuiAliasBind-----" + res.code)
										console.log("getuiAliasBind:" + res.code)
									})
								}
								service.saveLogInfo("getuiAliasGet:" + res.code)
							}
						}).catch(e => {
							console.log("getuiAliasGet:catch" + e);
						})
					} else {
						console.log("没有用户无法绑定个推别名")
						service.saveLogInfo("-----没有用户无法绑定个推别名-----")
					}
				} else {
					service.saveLogInfo("-----没有找到设备cid-----")
					console.log("-----没有找到getui设备cid-----")
				}
			},
			initUniCid() { // 个推cid
				service.saveLogInfo("-----initUniCid-----")
				// #ifdef APP-PLUS
				plus.push.getClientInfoAsync((info) => {
					let cid = info["clientid"];
					if (cid) {
						getApp().globalData.uniAppClientId = cid
						getApp().getuiAliasBind()
						service.saveLogInfo("-----cid-----" + cid)
					} else {
						// 如果没有获取到就再延迟获取一下 文档说明： https://uniapp.dcloud.net.cn/unipush-v1.html#_1-3-1-cid-%E8%8E%B7%E5%8F%96
						setTimeout(() => {
							plus.push.getClientInfoAsync((info) => {
								let cid = info["clientid"];
								if (cid) {
									getApp().globalData.uniAppClientId = cid
									getApp().getuiAliasBind()
									service.saveLogInfo("-----cid2-----" + cid)
								}
							});
						}, 1000)
					}
				});

				// #endif

			}
		}
	}
</script>

<style>
	/* #ifndef APP-PLUS-NVUE  */
	@import "public/colorui/main.css";
	@import "public/colorui/icon.css";

	.nav-list {
		display: flex;
		flex-wrap: wrap;
		padding: 0px 40upx 0px;
		justify-content: space-between;
	}

	.nav-li {
		padding: 30upx;
		border-radius: 12upx;
		width: 45%;
		margin: 0 2.5% 40upx;
		background-image: url(https://cdn.nlark.com/yuque/0/2019/png/280374/1552996358352-assets/web-upload/cc3b1807-c684-4b83-8f80-80e5b8a6b975.png);
		background-size: cover;
		background-position: center;
		position: relative;
		z-index: 1;
	}

	.nav-li::after {
		content: "";
		position: absolute;
		z-index: -1;
		background-color: inherit;
		width: 100%;
		height: 100%;
		left: 0;
		bottom: -10%;
		border-radius: 10upx;
		opacity: 0.2;
		transform: scale(0.9, 0.9);
	}

	.nav-li.cur {
		color: #fff;
		background: rgb(94, 185, 94);
		box-shadow: 4upx 4upx 6upx rgba(94, 185, 94, 0.4);
	}

	.nav-title {
		font-size: 32upx;
		font-weight: 300;
	}

	.nav-title::first-letter {
		font-size: 40upx;
		margin-right: 4upx;
	}

	.nav-name {
		font-size: 28upx;
		text-transform: Capitalize;
		margin-top: 20upx;
		position: relative;
	}

	.nav-name::before {
		content: "";
		position: absolute;
		display: block;
		width: 40upx;
		height: 6upx;
		background: #fff;
		bottom: 0;
		right: 0;
		opacity: 0.5;
	}

	.nav-name::after {
		content: "";
		position: absolute;
		display: block;
		width: 100upx;
		height: 1px;
		background: #fff;
		bottom: 0;
		right: 40upx;
		opacity: 0.3;
	}

	.nav-name::first-letter {
		font-weight: bold;
		font-size: 36upx;
		margin-right: 1px;
	}

	.nav-li text {
		position: absolute;
		right: 30upx;
		top: 30upx;
		font-size: 52upx;
		width: 60upx;
		height: 60upx;
		text-align: center;
		line-height: 60upx;
	}

	.text-light {
		font-weight: 300;
	}

	@keyframes show {
		0% {
			transform: translateY(-50px);
		}

		60% {
			transform: translateY(40upx);
		}

		100% {
			transform: translateY(0px);
		}
	}

	@-webkit-keyframes show {
		0% {
			transform: translateY(-50px);
		}

		60% {
			transform: translateY(40upx);
		}

		100% {
			transform: translateY(0px);
		}
	}

	/* #endif  */
</style>
